<script setup lang="ts">
import { bindMobileAPI, loginByQQAPI } from '@/apis/user';
import { codeRules, mobileRules } from '@/utils/rules';
import { onMounted, ref } from 'vue';

// 控制页面的显示
const isNeedBind = ref(false)
// 保存openId
const openId = ref('')

const mobile = ref('')
const code = ref('')

const store = useUserStore()
const router = useRouter()

// 发送短信验证码
import { userMobileCode } from '@/composables/useMobileCode'
import { useUserStore } from '@/stores';
import type { userType } from '@/types/user';
import { useRouter } from 'vue-router';
import { showSuccessToast } from 'vant';
// 调用组合式函数
const { onSend, time, formRef } = userMobileCode(mobile, 'bindMobile')

onMounted(() => {
    // 如果已经登录了
    if (QC.Login.check()) {
        QC.Login.getMe((id: string) => {
            // 获取openId
            openId.value = id
            // 调用接口函数
            loginByQQAPI(id)
                .then((res) => {
                    // 绑定成功 提示用户 跳转页面 将数据存储到本地存储里面
                    loginSuccess(res.data)
                })
                .catch(() => {
                    // 登陆失败 显示绑定手机号码的页面
                    isNeedBind.value = true
                })
        })
    }
})

// 登录成功的函数
const loginSuccess = (data: userType) => {
    // 存储到本地
    store.setUser(data)
    // 跳转页面
    router.replace('/user')
    // 提示用户
    showSuccessToast('登录成功')
}

// 点击绑定手机号
const onSubmit = async () => {
    const res = await bindMobileAPI({
        mobile: mobile.value,
        code: code.value,
        openId: openId.value
    })
    console.log(res.data)
    // 绑定成功 提示用户 跳转页面 将数据存储到本地存储里面
    loginSuccess(res.data)
}

</script>

<template>
    <div class="login-page" v-if="isNeedBind">
        <cp-nav-bar></cp-nav-bar>
        <div class="login-head">
            <h3>手机绑定</h3>
        </div>
        <van-form autocomplete="off" ref="formRef">
            <van-field name="mobile" placeholder="请输入手机号" v-model="mobile" :rules="mobileRules"></van-field>
            <van-field name="code" placeholder="请输入验证码" v-model="code" :rules="codeRules">
                <template #button>
                    <span class="btn-send" @click="onSend" :class="{ active: time > 0 }">{{ time > 0 ?
                        `${time}秒后重新发送验证码` :
                        '发送验证码' }}
                    </span>
                </template>
            </van-field>
            <div class="cp-cell">
                <van-button block round type="primary" native-type="submit" @click="onSubmit"> 立即绑定 </van-button>
            </div>
        </van-form>
    </div>
</template>


<style scoped lang="scss">
@import '@/styles/login.scss';
</style>